﻿using HW.Core.Dialog;
using HW.Core.Extension;
using HW.Logger;
using Orleans;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace HW.Core.Helper
{
    public class ExportHelper
    {
        public static bool Export<T>(ObservableCollection<T> array, string filename = null)
        {
            var t = typeof(T);
            var properties = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            var stringBuilder = new StringBuilder();

            //标题 
            foreach (var item in properties)
            {
                
                if (item.GetAlias() != null)
                {
                    stringBuilder.Append(item.GetAlias());
                }
                else
                {
                    stringBuilder.Append(item.Name);
                }
                
                stringBuilder.Append(",");
            }

            stringBuilder.Append("\r\n");

            //内容
            foreach (var model in array)
            {
                var row = new StringBuilder();
                foreach (var property in properties)
                {
                    var val = property.GetValue(model);
                    row.Append(val.ToString());
                    row.Append(",");
                }
                stringBuilder.Append(row.ToString());
                stringBuilder.Append("\r\n");
            }

            if (string.IsNullOrEmpty(filename))
            {
                var date = $"{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}";
                filename = $"{date}.csv";
            }
            else
            {
                filename = $"{filename}.csv";
            }

            //写入文件
            try
            {
                File.WriteAllText(filename, stringBuilder.ToString());
                return true;
            }
            catch (Exception e)
            {
                Logs.LogError(e);
                return false;
            }
            
        }
    }
}
